//
//  XGLoginViewController.m
//  HuanXin
//
//  Created by monkey on 2019/7/8.
//  Copyright © 2019 itcast. All rights reserved.
//

#import <SVProgressHUD/SVProgressHUD.h>
#import <Hyphenate/Hyphenate.h>

#import "XGLoginViewController.h"
#import "XGRegisterViewController.h"

#import "MBProgressHUD+Extension.h"

@interface XGLoginViewController ()

@property (weak, nonatomic) IBOutlet UITextField *userNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;

@end

@implementation XGLoginViewController

#pragma mark - 控制器生命周期方法

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(registerSuccessNotification:) name:XGRegisterSuccessNotificationName object:nil];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    DEBUG_Log_Method;
}

#pragma mark - 事件监听

// 注册
- (IBAction)registerAction:(UIButton *)sender
{
    XGRegisterViewController *viewController = [[XGRegisterViewController alloc] init];
    [self presentViewController:viewController animated:YES completion:nil];
}

// 登录
- (IBAction)loginAction:(UIButton *)sender
{
    [self.view endEditing:YES];
    
    if (!_userNameTextField.hasText || !_passwordTextField.hasText) {
        [SVProgressHUD showErrorWithStatus:@"用户名或密码为空"];
        return;
    }
    
    NSString *userName = [_userNameTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *password = [_passwordTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    [MBProgressHUD showMessage:@"正在登录…" toView:self.view];
    [[EMClient sharedClient] loginWithUsername:userName password:password completion:^(NSString *aUsername, EMError *aError) {
        [MBProgressHUD hideHUD];
        if (aError != nil) {
            DEBUG_Log(@"登录失败%@",aError.errorDescription);
            [SVProgressHUD showErrorWithStatus:@"登录失败!"];
            return;
        }
        
        [EMClient sharedClient].options.isAutoLogin = YES;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 发送通知 切换根控制器
            [[NSNotificationCenter defaultCenter] postNotificationName:XGSwitchApplicationRootViewControllerNotification object:nil userInfo:@{XGRootViewControllerClassNameKey: @"XGMainViewController"}];
        });
    }];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

// 注册成功通知监听
- (void)registerSuccessNotification:(NSNotification *)notification
{
    NSDictionary *info = notification.userInfo;
    _userNameTextField.text = info[@"userName"];
    _passwordTextField.text = info[@"password"];
}

@end
